package com.ccteam.shared.domain.moment

import com.ccteam.model.Resource
import com.ccteam.model.moment.MomentNoIdDTO
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.moment.MomentsRepository
import com.ccteam.shared.domain.SuspendUseCase
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/30
 *
 * 发布朋友圈Domain层
 */
class PublishMomentDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val momentsRepository: MomentsRepository
): SuspendUseCase<PublishMomentDataUseCase.PublishMomentRequest, Nothing?>(
    Dispatchers.IO
) {

    override suspend fun execute(parameters: PublishMomentRequest): Resource<Nothing?> {
        val userInfo = userCore.userInfo.value
        val isLogin = userCore.isLogin.value

        if(!isLogin || userInfo.userToken.isNullOrEmpty() || userInfo.userId.isNullOrEmpty()){
            return Resource.Error(ApiError.unknownCode,"非法操作")
        }

        return when(val result = momentsRepository.createMomentInfo(userInfo.userToken,
            MomentNoIdDTO(parameters.content,parameters.images,parameters.shareId,userInfo.userId,parameters.type)
        )){
            is ApiResult.Success -> {
                Resource.Success(null)
            }
            is ApiResult.Failure -> {
                Resource.Error(result.errorCode,result.errorMsg)
            }
            else -> {
                Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
        }
    }

    data class PublishMomentRequest(
        val type: Int,
        val content: String,
        val shareId: String?,
        val images: List<String>
    )
}